package com.itheima.servlet;

import com.itheima.bean.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.ArrayList;

@WebServlet("/listServlet")
public class ListServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String realPath = this.getServletContext().getRealPath("/stu.txt");
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(realPath), "utf-8"));
        String len;
        ArrayList<Student> list = new ArrayList<>();
        while ((len = br.readLine()) != null) {
            Student stu = new Student();
            String[] split = len.split(",");//按，进行切割
            stu.setUsername(split[0]);
            stu.setAge(Integer.parseInt(split[1]));
            stu.setPassword(Integer.parseInt(split[2]));
            list.add(stu);
        }
        br.close();
        HttpSession session = req.getSession();
        session.setAttribute("list",list);
        resp.sendRedirect("/stu/listStudent.jsp");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
